package proj.pt.web;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindException;
import org.springframework.validation.Errors;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import proj.pt.model.Course;
import proj.pt.model.Department;
import proj.pt.model.SubCourse;
import proj.pt.model.User;
import proj.pt.services.Role;

public class ProfileController extends CustomSimpleFormController {
	
	protected ModelAndView handleRequestInternal(HttpServletRequest request,
            HttpServletResponse response)
     throws Exception {
		
		ModelAndView mav = super.handleRequestInternal(request, response);
		// Getting user from session.
		User currentUser = (User)request.getSession().getAttribute("LOGIN_USER");
		
		// if current user is null OR
		// id is not equal to current logged in user's id
		if(currentUser == null){
			// redirect user to home page :)
			mav.setView(new RedirectView("home.pt"));
		} //end if
		
		return mav;
	}
	
	protected Object formBackingObject(HttpServletRequest request)
    throws Exception{
		User user = null;
		User currentUser = (User)request.getSession().getAttribute("LOGIN_USER");
		if(currentUser !=null && currentUser.getId() > -1){
			// load from database
			user = getLogicProcessor().getUser(currentUser.getId());
		} //end if
		
		// there may be chance that false id has given for loading from database, and that is not present there, so role will be null;
		if(user == null)
		return new User();
		else return user;
	}
	
	protected Map referenceData(HttpServletRequest request, Object command, Errors errors) throws Exception {
		Map dataMap = super.referenceData(request, command, errors);
		
		User user = (User)command;
		dataMap.put("roleMap", Role.getRoleMap());
		
		
		return dataMap;
	} //end referenceData
	
	protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
		binder.registerCustomEditor(Department.class, new DepartmentEditor(getLogicProcessor()));
		binder.registerCustomEditor(SubCourse.class, "subCourse", new SubCourseEditor(getLogicProcessor()));
		binder.registerCustomEditor(Course.class, "course", new CourseEditor(getLogicProcessor()));
		binder.registerCustomEditor(Date.class, "dob", new CustomDateEditor(new SimpleDateFormat("dd/MM/yyyy"), true));
	}
	
	protected boolean isFormChangeRequest(HttpServletRequest request, Object command) {
		String action = WebUtils.getAction(request);
		if("action_select".equals(action) || "action_course_select".equals(action)){
			return true;
		} //end if
		return false;
	}
	
		
	/**
	 * This method does the validation.
	 */
	protected void onBindAndValidate(HttpServletRequest request,
            Object command,
            BindException errors) throws Exception {
		
		// if no validation required, then just return from this method.
		if(!doValidate(request))return;
		
		User user = (User)command;
		
		// Validation based on role
		if(Role.ROLE_ADMIN_FULL_ACCESS.equals(user.getRoleId()) || Role.ROLE_ADMIN_VIEW_ONLY.equals(user.getRoleId())){
			// for admin
			
		} else if(Role.ROLE_HOD_FULL_ACCESS.equals(user.getRoleId()) || Role.ROLE_HOD_VIEW_ONLY.equals(user.getRoleId())){
			// for HOD
			if(!StringUtils.hasLength(user.getStaffId())){
				errors.reject("staffId.required", "Staff ID required.");
			} else if(!getLogicProcessor().validateStaffId(user)){
				errors.reject("staffId.exist", "Staff ID exist, please enter a unique Staff ID.");
			} //end if
			
		} else if(Role.ROLE_TUTOR_FULL_ACCESS.equals(user.getRoleId()) || Role.ROLE_TUTOR_VIEW_ONLY.equals(user.getRoleId())){
			// for tutor
			if(!StringUtils.hasLength(user.getStaffId())){
				errors.reject("staffId.required", "Staff ID required.");
			} else if(!getLogicProcessor().validateStaffId(user)){
				errors.reject("staffId.exist", "Staff ID exist, please enter a unique Staff ID.");
			} //end if
			
			
		} else if(Role.ROLE_STUDENT_FULL_ACCESS.equals(user.getRoleId()) || Role.ROLE_STUDENT_VIEW_ONLY.equals(user.getRoleId())){
			// for student
			if(!StringUtils.hasLength(user.getStudentId())){
				errors.reject("studentId.required", "Student ID required.");
			} else if(!getLogicProcessor().validateStudentId(user)){
				errors.reject("studentId.exist", "Student ID exist, please enter a unique Student ID.");
			} //end if
			
			if(!StringUtils.hasLength(user.getRegistrationNo())){
				errors.reject("registrationNo.required", "Registration No. required.");
			} else if(!getLogicProcessor().validateRegistrationNo(user)){
				errors.reject("registrationNo.exist", "Registration No. exist, please enter a unique Registration No.");
			} //end if
			
		}
		
		if(!StringUtils.hasLength(user.getName())){
			errors.reject("name.required", "Name of User required.");
		} //end if
		
		
		// if Update login is selected then ...
		if(user.getUpdateLoginDetails()){
			if(!StringUtils.hasLength(user.getNewPassword())){
				// password not provided
				errors.reject("password.required", "Password required");
			} else if(!StringUtils.hasLength(user.getRetypePassword())){
				// retype-password not provided
				errors.reject("retypepassword.required", "`Retype Password` field cannot be empty");
			} else if(!user.getNewPassword().equals(user.getRetypePassword())){
				// password doesn't match
				errors.reject("retypepassword.nomatch", "`Password` and `Retype Password` are not same.");
			}
		} //end if
	}
	
		
	protected ModelAndView onSubmit(HttpServletRequest request,
            HttpServletResponse response,
            Object command,
            BindException errors)
     throws Exception {
		
		String action = WebUtils.getAction(request);
					
		if("action_save".equals(action)){
			getLogicProcessor().saveOrUpdateUser((User)command);
		} else if("action_delete".equals(action)){
			// do nothing
		} else if("action_cancel".equals(action)){
			// do nothing
		} else{
			// do nothing.
		} 
		
		ModelAndView  mav = new ModelAndView();
		mav.setView(new RedirectView(getSuccessURI()));
		return mav;
	} //end onSubmit	
	
}
